import os
from werkzeug.utils import secure_filename

class FileHandler:
    """文件处理工具类"""
    
    ALLOWED_EXTENSIONS = {'csv'}
    
    def allowed_file(self, filename: str) -> bool:
        """检查文件扩展名是否允许"""
        return '.' in filename and \
               filename.rsplit('.', 1)[1].lower() in self.ALLOWED_EXTENSIONS
    
    def get_file_size(self, filepath: str) -> str:
        """获取文件大小"""
        size_bytes = os.path.getsize(filepath)
        
        if size_bytes < 1024:
            return f"{size_bytes} B"
        elif size_bytes < 1024 * 1024:
            return f"{size_bytes / 1024:.1f} KB"
        else:
            return f"{size_bytes / (1024 * 1024):.1f} MB"
    
    def clean_old_files(self, directory: str, max_age_hours: int = 24):
        """清理旧文件"""
        import time
        current_time = time.time()
        
        for filename in os.listdir(directory):
            filepath = os.path.join(directory, filename)
            if os.path.isfile(filepath):
                file_age = current_time - os.path.getctime(filepath)
                if file_age > max_age_hours * 3600:  # 转换为秒
                    os.remove(filepath)